package IOTest;

import java.io.*;

class Person implements Serializable {
    private static final long serialVersionUID = 281974987149887234L;
    private String name;
    private int age;
    private static String country = "China";
    private transient String password = "123456"; // transient修饰的字段不会被序列化

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String toString() {
        return "name = " + name + ", age = " + age + ", country = " + country + ", password = " + password;
    }
}

public class ObjectStream {
    public static void main(String[] args) {
        String filename = testObjectOutputStream();
        testObjectInputStream(filename);
    }

    public static String testObjectOutputStream() {
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
            oos.writeObject(new Person("Jack", 23));
            oos.flush(); // 刷新操作，将内存中的数据写入文件
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (oos != null) {
                try {
                    oos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return "object.dat";
    }

    public static void testObjectInputStream(String filename) {
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(new FileInputStream(filename));
            Object obj = ois.readObject();
            System.out.println(obj); // name = Jack, age = 23, country = China, password = null
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ois != null) {
                try {
                    ois.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
